package io.github.yotta.common.web.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author yotta
 * @date 2023/5/16 10:36
 * 用于处理统一处理filter异常，将filter异常统一交付自定义的异常处理起处理
 * 因为spring的异常处理器（@RestControllerAdvice）是无法捕获filter执行期间的异常并处理的
 *
 */
@Slf4j
public class FilterChainExceptionHandlerFilter implements Filter {

    /**
     * 过滤器顺序，数字越小，越先执行
     * 当前过滤器需要最先执行，才能捕获其他过滤器的异常
     */
    public final static Integer ORDER = Integer.MIN_VALUE;

    private final HandlerExceptionResolver resolver;

    public FilterChainExceptionHandlerFilter(HandlerExceptionResolver resolver) {
        this.resolver = resolver;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            chain.doFilter(request, response);
        } catch (Exception e) {
            log.error("filter chain RuntimeException , cause:{}", e.getMessage(), e);
            resolver.resolveException((HttpServletRequest) request, (HttpServletResponse) response, null, e);
        }
    }
}
